package com.auto.survey.geocom

import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import kotlinx.coroutines.suspendCancellableCoroutine
import java.lang.ref.WeakReference
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class GeoComExecutCore(bluetoothmanager: BluetoothManagerUtil, geoCom: GeoCom, helper: GeoComHelper) : IGeoComExecutor {

    private val bluetoothRef = WeakReference(bluetoothmanager)
    private val helperRef = WeakReference(helper)
    private val geoCom = geoCom

    override suspend fun execute(): String {
        return suspendCancellableCoroutine { continuation ->
            // 检查蓝牙连接
            val devices = bluetoothRef.get()?.getConnectedDevices2()
            if (devices.isNullOrEmpty()) {
                continuation.resumeWithException(IllegalStateException("没有连接的蓝牙设备"))
                return@suspendCancellableCoroutine
            }

            val device = devices[0]

            // 设置一次性回调

            val callback = object:(String)->Unit {
                override fun invoke(result: String) {
                    // 立即注销回调，防止重复调用
                    helperRef.get()?.removeReceiveBtnInfoCallback()
                    if (!continuation.isCancelled) {
                        continuation.resume(result)
                    }
                }

            }
            helperRef.get()?.receiveBtInfoCallback(callback)
            // 协程取消时的处理
            continuation.invokeOnCancellation {
                helperRef.get()?.removeReceiveBtnInfoCallback()
            }

            // 发送数据
            try {
                bluetoothRef.get()?.sendDataByClient(device, geoCom.command.toByteArray())
            } catch (e: Exception) {
                if (!continuation.isCancelled) {
                    continuation.resumeWithException(e)
                }
            }

        }
    }

    override fun getGeoCom(): GeoCom {
       return geoCom
    }
}